var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var mongoose = require('mongoose');
var ObjectId = require('mongoose').Types.ObjectId;
var Keyword = require('../models/keywords').Keyword;
var KeywordStat = require('../models/keywordStats').KeywordStat;


// 链接数据库
mongoose.connect('mongodb://contentbank:ContentBank4.2@111.204.165.5:27017/contentbank');
//mongoose.connect('mongodb://127.0.0.1:27017/scrapy');

mongoose.connection.on('error', function(err) {
    console.log(err);
});
mongoose.connection.once('open', function(callback) {
    console.log('连接成功');
});



var getQuery = function(req) {
    var params = {
        'skip': Number(req.query.skip) || 0,
        'limit': Number(req.query.limit) || 100
    };
    console.log(' skip:' + params.skip + ' limit:' + params.limit);
    return params;
};
// 列表页
router.get('/', function(req, res) {
    Keyword.find().lean().exec(function(err, docs) {
        if (err) {
            console.log('error');
        }

        res.render('pages/keywords/index', {
            layout: 'layout/admin',
            controller: 'keywords',
            action: 'index',
            data: {
                docs: docs
            }
        });
    });
});
// 新建页
router.get('/new', function(req, res) {
    res.render('pages/keywords/new', {
        layout: 'layout/admin',
        controller: 'keywords',
        action: 'new',
        data: {}
    });
});
// 编辑页
router.get('/:id/edit', function(req, res) {
    Keyword.findOne({
        '_id': new ObjectId(req.params.id)
    }).lean().exec(function(err, doc) {
        if (err) {
            console.log('error');
        }
        console.log(doc);

        res.render('pages/keywords/edit', {
            layout: 'layout/admin',
            controller: 'keywords',
            action: 'edit',
            data: {
                doc: doc
            }
        });
    });
});
// 新建/编辑keyword
router.post('/', function(req, res) {
    var kw;

    if (req.body.id) {
        Keyword.where({
            '_id': new ObjectId(req.body.id)
        }).update({
            title: req.body.title,
            nicks: req.body.nicks.split(','),
            description: req.body.description
        }, function(err) {
            if (err) {
                console.log(err);
            }
            res.redirect('/keywords');
        });
    } else {
        kw = new Keyword({
            title: req.body.title,
            nicks: req.body.nicks.split(','),
            description: req.body.description
        });

        kw.save(kw, function(err) {
            if (err) {
                console.log(err);
            }
            res.redirect('/keywords');
        });
    }
});
// 删除
router.delete('/', function(req, res) {
    var ret = {};

    if (req.body.id) {
        Keyword.where({
            '_id': new ObjectId(req.body.id)
        }).remove({}, function(err) {
            if (err) {
                console.log(err);
                ret.status = false;
            }

            ret.status = true;
            res.json(ret);
        });
    }
});



// 传播力指数页
router.get('/:id/spread', function(req, res) {
    var spreadRelateWords,
        spreadReportStatistic;

    KeywordStat.find({
        keyword_id: new ObjectId(req.params.id)
    }, {
        spread_relate_words: 1,
        spread_report_statistic: 1,
        stat_time: 1
    }).lean().exec(function(err, docs) {
        if (err) {
            console.log(err);
        }
        if (docs && docs.length) {
            spreadRelateWords = docs[docs.length - 1].spread_relate_words;
            spreadReportStatistic = docs.filter(function(doc) {
                return doc.spread_report_statistic;
            }).map(function(doc) {
                return doc.spread_report_statistic;
            });
        }

        res.render('pages/keywords/spread', {
            layout: 'layout/admin',
            controller: 'keywords',
            action: 'spread',
            data: {
                keyword_id: req.params.id,
                spreadRelateWords: JSON.stringify(spreadRelateWords || {}),
                spreadReportStatistic: JSON.stringify(spreadReportStatistic || {})
            }
        });
    });
});
// 收视指数页
router.get('/:id/tv', function(req, res) {
    var tvRetainedStatistic,
        tvSocialStatistic,
        tvBroadcastStatistic,
        tvRelateWords;

    KeywordStat.find({
        keyword_id: new ObjectId(req.params.id)
    }, {
        // tv_top_media: 1,
        tv_retained_statistic: 1,
        tv_social_statistic: 1,
        tv_broadcast_statistic: 1,
        tv_relate_words: 1
    }).lean().exec(function(err, docs) {
        if (err) {
            console.log('error');
        }

        if (docs && docs.length) {
            tvRelateWords = docs[docs.length - 1].tv_relate_words;
            tvBroadcastStatistic = docs.filter(function(doc) {
                return doc.tv_broadcast_statistic;
            }).map(function(doc) {
                return doc.tv_broadcast_statistic;
            });

            tvRetainedStatistic = docs.filter(function(doc) {
                return doc.tv_retained_statistic;
            }).map(function(doc) {
                return doc.tv_retained_statistic;
            });

            tvSocialStatistic = docs.filter(function(doc) {
                return doc.tv_social_statistic;
            }).map(function(doc) {
                return doc.tv_social_statistic;
            });
        }

        console.log(tvBroadcastStatistic);

        res.render('pages/keywords/tv', {
            layout: 'layout/admin',
            controller: 'keywords',
            action: 'tv',
            data: {
                keyword_id: req.params.id,
                // tvTopMedia: JSON.stringify(doc.tv_top_media || {}),
                tvRetainedStatistic: JSON.stringify(tvRetainedStatistic || {}),
                tvSocialStatistic: JSON.stringify(tvSocialStatistic || {}),
                tvBroadcastStatistic: JSON.stringify(tvBroadcastStatistic || {}),
                tvRelateWords: JSON.stringify(tvRelateWords || {})
            }
        });
    });
});

// sns指数页
router.get('/:id/sns', function(req, res) {
    Keyword.findOne({
        _id: new ObjectId(req.params.id)
    }, {
        sns_tieba_statistic: 1,
        sns_douban_statistic: 1,
        sns_weibo_statistic: 1,
        sns_video_statistic: 1,
        sns_relate_words: 1
    }).lean().exec(function(err, doc) {
        if (err) {
            console.log('error');
        }

        res.render('pages/keywords/sns', {
            layout: 'layout/admin',
            controller: 'keywords',
            action: 'sns',
            data: {
                doc: doc,
                snsTieStatistic: JSON.stringify(doc.sns_tieba_statistic || {}),
                snsDoubanStatistic: JSON.stringify(doc.sns_douban_statistic || {}),
                snsWeiboStatistic: JSON.stringify(doc.sns_weibo_statistic || {}),
                snsVideoStatistic: JSON.stringify(doc.sns_video_statistic || {}),
                snsRelateWords: JSON.stringify(doc.sns_relate_words || {})
            }
        });
    });

});



// 微信指数页
router.get('/:id/wechat', function(req, res) {
    var wechatPlaylike,
        wechatRelateWords,
        wechatTendency;

    KeywordStat.find({
        keyword_id: new ObjectId(req.params.id)
    }, {
        wechat_playlike: 1,
        wechat_relate_words: 1,
        wechat_tendency: 1
    }).lean().exec(function(err, docs) {
        if (err) {
            console.log('error');
        }

        if(docs && docs.length){
            wechatPlaylike = docs.filter(function(doc){
                return doc.wechat_playlike;
            }).map(function(doc){
                return doc.wechat_playlike;
            });

            wechatRelateWords = docs[docs.length -1].wechat_relate_words;

            wechatTendency = docs[docs.length -1].wechat_tendency;
        }

        res.render('pages/keywords/wechat', {
            layout: 'layout/admin',
            controller: 'keywords',
            action: 'wechat',
            data: {
                keyword_id: req.params.id,
                wechatPlaylike: JSON.stringify(wechatPlaylike || {}),
                wechatRelateWords: JSON.stringify(wechatRelateWords || {}),
                wechatTendency: JSON.stringify(wechatTendency || {})
            }
        });
    });
});



//spread
router.get('/:id/spread_relate_words.json', function(req, res, next) {
    var params = getQuery(req),
        ret = {};
    Keyword.find_spread_relate_words(req.params.id, function(err, docs) {
        if (err) {
            console.log('error');
        }
        ret.status = true;
        ret.data = docs;

        res.json(ret);
    });
});




module.exports = router;
